﻿using Infrastructures;
using System;
using System.Configuration;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.SessionState;
using ConcreteService;
using System.Text;
using System.Web.UI;

namespace SponsorshipWeb
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_PostAuthorizeRequest()
        {
            if (IsWebApiRequest())
            {
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            }
        }

        private bool IsWebApiRequest()
        {
            return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(String.Format("~/{0}", "api"));
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            string conn = ConfigurationManager.ConnectionStrings["DbString"].ConnectionString;
            string provider = ConfigurationManager.ConnectionStrings["DbProvider"].ConnectionString;
            string strDBConn = ConfigurationManager.AppSettings["MangoDB"];
            string strDBName = ConfigurationManager.AppSettings["MangoDBName"];

            DBHelper.CreateMySqlDBConn(conn, provider);
            DBHelper.CreateMangoDBConn(strDBConn, strDBName);

            FactoryCreator.Initialize();
            AppConfig.RefreshBaseData();
        }

        protected void Application_Error()
        {
            Exception ex = Server.GetLastError();

            Response.Clear();
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;

            var user = AuthUtil.GetAuthentication();
            LogUtil.CreateForException(ex, user == null ? "system" : user.UserID.ToString(), this.Request == null ? "" : this.Request.RawUrl);

            if (this.Request != null && this.Request.RawUrl.Contains(".html"))
            {
                if (this.Request.RawUrl.Contains("?"))
                    Server.Transfer(this.Request.RawUrl + "&ex=1", false);
                else
                    Server.Transfer(this.Request.RawUrl + "?ex=1", false);
            }
        }
    }
}
